/**
 * Created by lumix on 2015/4/22.
 */
var express = require('express');
var router = express.Router();
var Promise = require('promise');
var logger = require('log4js').getLogger('member');
var commonUtils = require('./../../utils/commonUtils');
var mailUtil = require('./../../utils/mail');
var memberService = require('../service/MemberService');
var articleService = require('../service/ArticleService')
var config = require('../../../config')
var multiparty = require('multiparty');
var attentionService = require('../service/AttentionService');
var logFilter = require('./../../utils/logFilter');
var util = require('util');
var fs = require('fs');
var imageinfo = require('imageinfo');


router.post('/attention',function(req,res,next){
    var memberId = req.body.memberId;
    var attentionId = req.body.attentionId;
    if(!memberId||!attentionId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    var attention = {};
    attention.articleId = attentionId;
    attention.memberId = memberId;
    attention.status = 1;
    memberService.attention(attention).then(function(r){
        if(r){
            return Promise.resolve(r);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            return memberService.getById(attentionId).then(function(member){
                if(member){
                    if(r==99){
                        member.hasAttention = true;
                    }
                    return Promise.resolve(member);
                }else{
                    return Promise.resolve(null);
                }
            })

        }else{
            return Promise.resolve(null);
        }
    }).then(function(member){
        if(member){
            if(member.hasAttention){
                return Promise.resolve(member);
            }else{
                var fansNum = member.fansNum;
                fansNum++;
                member.fansNum = fansNum;
                member.updateTime = new Date();
                return memberService.plasFans(member).then(function(r){
                    if(r){
                        return Promise.resolve(r);
                    }else{
                        return Promise.resolve(null);
                    }
                })
            }

        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })


})



router.post('/unAttention',function(req,res,next){
    var memberId = req.body.memberId;
    var attentionId = req.body.attentionId;
    if(!memberId||!attentionId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    var attention = {};
    attention.articleId = attentionId;
    attention.memberId = memberId;
    attention.status = 1;
    memberService.unAttention(attention).then(function(r){
        if(r){
            return Promise.resolve(r);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            return memberService.getById(attentionId).then(function(member){
                if(member){
                    if(r==99){
                        member.hasUnAttention = true;
                    }
                    return Promise.resolve(member);
                }else{
                    return Promise.resolve(null);
                }
            })

        }else{
            return Promise.resolve(null);
        }
    }).then(function(member){
        if(member){
            if(member.hasUnAttention){
                return Promise.resolve(member);
            }else{
                var fansNum = member.fansNum;
                fansNum--;
                member.fansNum = fansNum;
                member.updateTime = new Date();
                return memberService.plasFans(member).then(function(r){
                    if(r){
                        return Promise.resolve(r);
                    }else{
                        return Promise.resolve(null);
                    }
                })
            }

        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })


})
//个人中心首页
router.post('/center',logFilter.saveArticleLog,function (req,res,next) {
    var memberId = req.body.memberId;
    var type = req.body.type;
    var pageNo = req.body.pageNo;
    var myMemberId = req.body.myMemberId;
    var pageSize = 5;
    if(!pageNo){pageNo=1};
    if(!type){type = 1;}
    if(type==2){
        pageSize = 8;
    }
    if(!memberId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    memberService.getById(memberId).then(function(member){
        if(member){
            return Promise.resolve(member);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(member){
        if(member){
            //获取关注的数量
            return memberService.getAttentionNum(memberId).then(function(r){
                member.attentionNum = r;
                return Promise.resolve(member);

            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(member){
        //获取收藏数量
        if(member){
            return memberService.getCollectNum(memberId).then(function(r){
                member.collectNum = r;
                return Promise.resolve(member);
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(member){

        if(member){
            if(type==1){

                return memberService.getMyArticle(memberId,pageNo,pageSize).then(function(articles){
                    var data = {};
                    data.member = member;
                    data.articles = articles;
                    return Promise.resolve(data);
                }).then(function (data) {
                    if(data.articles){
                        var queue = [];
                        var tempMemberId = memberId;
                        if(myMemberId){tempMemberId = myMemberId};
                        data.articles.forEach(function (item) {
                            item.likeFlag = false;
                            queue.push(articleService.checkLike(myMemberId,item.id).then(function (hasLike) {
                                if(hasLike&&hasLike.length>0){
                                    item.likeFlag = true;
                                }
                                return Promise.resolve(item);
                            }))

                        })
                        return Promise.all(queue).then(function () {
                            return Promise.resolve(data);
                        })
                    }

                })
            }else if(type==2){
                return memberService.getAttention(memberId,pageNo,pageSize).then(function(attentions){
                    var data = {};
                    data.member = member;
                    data.attentions = attentions;
                    return Promise.resolve(data);
                })
            }else if(type==3){
                return memberService.getCollect(memberId,pageNo,pageSize).then(function(collects){
                    var data = {};
                    data.member = member;
                    data.collects = collects;
                    return Promise.resolve(data);
                }).then(function (data) {
                    if(data.collects){
                        var queue = [];
                        var tempMemberId = memberId;
                        if(myMemberId){tempMemberId = myMemberId};
                        data.collects.forEach(function (item) {
                            item.likeFlag = false;
                            queue.push(articleService.checkLike(tempMemberId,item.id).then(function (hasLike) {
                                if(hasLike&&hasLike.length>0){
                                    item.likeFlag = true;
                                }
                                return Promise.resolve(item);
                            }))

                        })
                        return Promise.all(queue).then(function () {
                            return Promise.resolve(data);
                        })
                    }else{
                        return Promise.resolve(data);
                    }

                })
            }

        }else{
            return Promise.resolve(null);
        }
    }).then(function (data) {
        if(data&&!myMemberId&&type==1){//进入自己个人中心
            var queue = [];
            data.articles.forEach(function (item) {
                queue.push(articleService.getUnLookCommentNum(item.id).then(function (num) {
                    item.unLookCommentNum = num;
                    return Promise.resolve(item);
                }))
            })
            return Promise.all(queue).then(function () {
                return Promise.resolve(data);
            })

        }else if(data&&myMemberId&&type==1){
            //获取别人的未读收藏
            return memberService.getUnLookCollectNum(myMemberId,memberId).then(function (num) {
                data.member.unLookCollectNum = num;
                return Promise.resolve(data);
            })
        }else{
            return Promise.resolve(data);
        }
    }).then(function (data) {
        //计算图片宽高
        if(type==1){
            if(data.articles){
                data.articles.forEach(function (item) {
                    if(item&&item.bak4){
                        var imageData = fs.readFileSync(config.main.fileUploadPath+item.bak4);
                        var info = imageinfo(imageData);
                        item.imageWidth = info.width;
                        item.imageHeight = info.height;
                    }
                })
                
            }

        }else if(type==3){
            if(data.collects){
                data.collects.forEach(function (item) {
                    if(item&&item.bak4){
                        var imageData = fs.readFileSync(config.main.fileUploadPath+item.bak4);
                        var info = imageinfo(imageData);
                        item.imageWidth = info.width;
                        item.imageHeight = info.height;
                    }
                })
            }
        }
        return Promise.resolve(data);
    }).then(function(data){
        if(data){
            res.json({'success':true,'data':data});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })


})

//个人信息
router.post('/info',function(req,res,next){
    var memberId = req.body.memberId;
    if(!memberId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    memberService.getById(memberId).then(function(member){
        if(member){
            return Promise.resolve(member);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(member){
        if(member){
            //获取关注的数量

            return memberService.getAttentionNum(memberId).then(function(r){
                member.attentionNum = r;
                return Promise.resolve(member);

            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(member){
        //获取收藏数量
        if(member){
            return memberService.getCollectNum(memberId).then(function(r){
                member.collectNum = r;
                return Promise.resolve(member);
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function (member) {
        if(member){
            return memberService.getAllUnLooKCommentNum(memberId).then(function (num) {
                member.allUnLookCommentNum = num;
                return Promise.resolve(member);
            })
        }else{
            return Promise.resolve(null);
        }

    }).then(function (member) {
        if(member){
            return memberService.getAllAttentionUnLooKNum(memberId).then(function (num) {
                member.allAttentionUnLooKNum = num;
                return Promise.resolve(member);
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(member){
        if(member){
            var data = {};
            data.member = member;
            res.json({'success':true,'data':data});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        logger.error(err);
        console.log(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})


router.post('/updatePW', function (req, res, next) {
    var memberId = req.body.memberId;
    var oldPW = req.body.oldPW;
    var newPW = req.body.newPW;

    if(!memberId||!oldPW||!newPW){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    
    memberService.getById(memberId).then(function (m) {
        if(m){
            var password = m.password;
            if(password==oldPW){
                return Promise.resolve(m);
            }else{
                return Promise.resolve(1);
            }

        }else{
            return Promise.resolve(2);
        }
    }).then(function(m){
        if(m&& m.id){
            m.password = newPW;
            m.updateTime = new Date();
            return memberService.updatePW(m).then(function(result){
                if(result){
                    return Promise.resolve(0);
                }else{
                    return Promise.resolve(null);
                }
            })
        }else{
            return Promise.resolve(m);
        }
    }).then(function (result) {
        if(0==result){
            res.json({'success':true});
        }else if(1==result){
            res.json({'success':false,'msg':'原密码错误'});
        }else if(2==result){
            res.json({'success':false,'msg':'错误的账户信息'});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    }, function (err) {
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})

router.post('/findPW', function (req,res,next) {
    var mail = req.body.mail;
    if(!mail){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    memberService.getByMail(mail).then(function (m) {
        if(m&& m.length>0){
            return Promise.resolve(m[0]);
        }else{
            return Promise.resolve(1);
        }
    }).then(function (m) {
        if(m&& m.id){
            var password = m.password;
            var msg = '您的密码是'+password+',请妥善保管。';
            return mailUtil.sendMail(mail,msg).then(function(result){

                return Promise.resolve(result);
            })
        }else{
            return Promise.resolve(m);
        }
    }).then(function (result) {
        console.log(result);
        if(1==result){
            res.json({'success':false,'msg':'无效的邮箱'});
        }else{
            res.json({'success':true});
        }

    }, function (err) {
        console.log(err);
        res.json({'success':false,'msg':'网络异常'});
    })
})

router.post('/updateHead', function (req, res, next) {
    var form = new multiparty.Form();
    form.encoding = 'utf-8';
    form.uploadDir = config.main.fileUploadPath;
    form.parse(req, function(err, fields, files) {
        var memberId = fields.memberId[0];
        new Promise(function(fulfil,reject){
            if(err){
                reject(null);
            }else{
                fulfil(files);
            }
        }).then(function(files){
                if(!files){
                    return Promise.resolve(null);
                }else{
                    var item = files.upload[0];
                    return articleService.getFileName(item,0);
                }
            }).then(function(fileName){
                return memberService.getById(memberId).then(function (m) {
                    if(m){
                        m.headImgUrl = fileName;
                        m.updateTime = new Date();
                        return Promise.resolve(m);
                    }else{
                        return Promise.resolve(null);
                    }
                })
            }).then(function (m) {
                if(m){
                    return memberService.updatePW(m).then(function (r) {
                        if(r){
                            return memberService.updateHead(m.id,m.headImgUrl).then(function () {
                                return Promise.resolve(m.headImgUrl);
                            })
                        }else{
                            return Promise.resolve(null);
                        }
                    });
                }else{
                    return Promise.resolve(null);
                }
            }).then(function (result) {
                if(result){
                    res.json({'success':true,'fileName':result});
                }else{
                    res.json({'success':false,'msg':'操作失败'});
                }
            },function(err){
                console.log(err);
                logger.error(err);
                res.json({'success':false,'msg':'网络异常'});
            })
    })

})

router.post('/updateInfo', function (req, res, next) {
    var memberId = req.body.memberId;
    var info = req.body.info;
    var type = req.body.type;
    if(!memberId||!info||!type){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }

    memberService.getById(memberId).then(function(m){
        if(m){
            return Promise.resolve(m);
        }else{
            return Promise.resolve(1);
        }
    }).then(function (m) {
        if(m==1){
            return Promise.resolve(m);
        }else{
            if(type==1){
                m.username = info;
            }else if(type==2){
                m.phone = info;
            }else if(type==3){
                m.email = info;
            }
            m.updateTime = new Date();
            return memberService.updatePW(m).then(function (result) {
                console.log(result);
                if(!result){
                    return Promise.resolve(null);
                }else{
                    return Promise.resolve(0);
                }
            })
        }
    }).then(function(result){
        if(1==result){
            res.json({'success':false,'msg':'错误的账户信息'});
        }else if(0==result){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    }, function (err) {
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})

router.post('/nexus', function (req, res, next) {
    var memberId = req.body.memberId;
    var myMemberId = req.body.myMemberId;
    var status = req.body.status;
    var pageNo = req.body.pageNo;
    if(!pageNo){
        pageNo = 1;
    }
    var pageSize = 8;
    if(!memberId||!status){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    attentionService.getNexus(memberId,status,pageNo,pageSize).then(function(atts){
        return Promise.resolve(atts);
    }).then(function (atts) {
        if(atts&&atts.length>0){
            var queue = [];
            atts.forEach(function (item) {
                var memberId = 0;
                if(status == 1){
                    memberId = item.articleId;
                }else{
                    memberId = item.memberId;
                }
                queue.push(memberService.getById(memberId));
            })
            return Promise.all(queue);
        }else{
            return Promise.resolve(null);
        }
    }).then(function (mems) {

        var tempMems = [];
        if(mems&&mems.length>0){
            mems.forEach(function (item) {
                if(item&&item.id){
                    tempMems.push(item);
                }
            })
            mems = tempMems;
            if(myMemberId&&mems&&mems.length>0&&status==1){//获取关注人未读
                var queue = [];
                mems.forEach(function (item) {
                    if(item&&item.id){
                        var attentionMemberId= item.id;
                        queue.push(memberService.getAttentionUnLooKNum(myMemberId,attentionMemberId).then(function (num) {
                            item.attentionUnLooKNum = num;
                            return Promise.resolve(item);
                        }))
                    }

                })
                return Promise.all(queue).then(function () {
                    return Promise.resolve(mems);
                });
            }else{
                return Promise.resolve(mems);
            }
        }else{

            return Promise.resolve(null);
        }

    }).then(function (mems) {
            var data = {};
            data.members = mems;
            res.json({'success':true,'data':data});
    }, function (err) {
        console.log(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})

module.exports = router;
